package com.ls.lsqc.modules.sys.web;


import com.ls.lsqc.modules.sys.utils.SystemMessageUtils;
import groovy.util.ResourceException;
import freemarker.template.Configuration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ls.lsqc.common.beanvalidator.BeanValidators;
import com.ls.lsqc.common.config.Global;
import com.ls.lsqc.common.persistence.AjaxDone;
import com.ls.lsqc.common.persistence.BaseEntity;
import com.ls.lsqc.common.persistence.Page;
import com.ls.lsqc.common.utils.CollectionsUtils;
import com.ls.lsqc.common.utils.FileUtils;
import com.ls.lsqc.common.utils.ResourcesUtil;
import com.ls.lsqc.common.utils.StringUtils;
import com.ls.lsqc.common.utils.excel.ExportExcel;
import com.ls.lsqc.common.utils.excel.ImportExcel;
import com.ls.lsqc.common.web.BaseController;
import com.ls.lsqc.modules.sys.entity.Dict;
import com.ls.lsqc.modules.sys.service.DictService;

/**
 * @author 曹学海
 * @ClassName: DictController
 * @Description: 基准数据
 * @date 2016年11月1日 下午3:15:19
 */

@Controller
@RequestMapping(value = "${adminPath}/database/message/")
public class DictController extends BaseController {

    @Autowired
    // 保存 编辑 删除 方法
    private DictService dictService;

    @Autowired
    Configuration freemarkerConfiguration;

    //子项session
    private final String DICTSUBLIST = "dictSubList";

    @ModelAttribute
    public Dict get(@RequestParam(required = false) String id) {

        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {
            // 执行查询语句 查询基本信息
            return dictService.get (Long.parseLong (id));
        } else {

            // 若为空，实例化
            return new Dict ();
        }
    }

    /**
     * 进入一览页面
     *
     * @return
     */
    @RequiresPermissions("database:message:view")
    @RequestMapping(value = {"list", ""})
    public String list() {

        // 返回页面地址
        return "modules/sys/dictList";
    }

    /**
     * @Title: 画面检索
     * @Description: 查询页面
     */

    @RequiresPermissions("database:message:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(Dict dict, HttpServletRequest request, HttpServletResponse response, Model model)
            throws Exception {

        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        FileUtils filUtils = new FileUtils ();
        DateFormat dateForamat = new SimpleDateFormat ("yyyy-MM-dd HH:mm");

        // ajax回调时使用的一览list名
        request.setAttribute (Global.LIST_NAME, "dict");

        // 画面取得的检索项目
        //数据代码
        String itemCode = dict.getItemCode ();
        //数据中文
        String itemNameCn = dict.getItemNameCn ();
        //数据英文
        String itemNameEn = dict.getItemNameEn ();
        //数据日文
        String itemNameJp = dict.getItemNameJp ();

        String strUri = request.getContextPath () + Global.getAdminPath ();
        // 拼接字符串供分页使用
        String searchParam = "&itemCode=" + itemCode + "&itemNameCn=" + itemNameCn + "&itemNameEn=" + itemNameEn + "&itemNameJp=" + itemNameJp;
        // 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);

        // 查询一览页面数据
        Page <Dict> page = dictService.findList (new Page <Dict> (request, response), dict);

        // 读取系统路径
        // 读取文件生成字符串

        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("dicts", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("Dict.ftl"), map);
        listMap.put ("dict", strHtml);
        listMap.put ("page", page.getHtml ());

        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     *
     * @param filePath
     * @return html
     */
    public String readTxtFile(String filePath) {
        String strHtml = "";
        try {
            String encoding = "UTF-8";
            File file = new File (filePath);
            // 判断文件是否存在
            if (file.isFile ()) {
                InputStreamReader read = new InputStreamReader (
                        // 考虑到编码格式
                        new FileInputStream (file), encoding);
                BufferedReader bufferedReader = new BufferedReader (read);
                String lingText = null;
                while ((lingText = bufferedReader.readLine ()) != null) {
                    strHtml += lingText;
                }
                read.close ();
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return strHtml;
    }


    /**
     * 进入查看页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:view")
    @RequestMapping(value = "show")
    public String show(Dict dict, Model model) {

        // 执行查询方法查询子项数据为0的数据
        List <Dict> dictListFind = dictService.findList (dict);
        // 执行查询方法查询子项数据
        List <Dict> dictList = dictService.findListDict (dict);

        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dictListFind", dictListFind);
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dictList", dictList);
        dict.setOldItemValue (dict.getItemCode ());
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dict", dict);
        // 返回页面地址
        return "modules/sys/dictListShow";
    }


    /**
     * 进入状态信息页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:view")
    @RequestMapping(value = "statusmessages")
    public String statusmessages(Dict dict, Model model) {
        // 实例化子项
        Dict dictSub = new Dict ();
        // 将项目值赋给子项实体类
        dictSub.setItemValue (dict.getItemValue ());

        // 执行查询语句
        List <Dict> dictList = dictService.findSubDict (dictSub);

        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dictList", dictList);

        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dict", dict);

        // 返回页面地址
        return "modules/sys/dictShow";
    }


    /**
     * 进入编辑页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "form")
    public String form(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        // 新建判断 若不为null 编辑数据
        if (dict.getId () != null) {

            // 实力化子项实体类
            Dict dictSub = new Dict ();

            // 给子项实体类赋值（关联值——项目值）
            dictSub.setItemCode (dict.getItemCode ());

            // 执行查询方法查询子项数据
            List <Dict> dictList = dictService.findListDict (dictSub);
            // 执行查询方法查询子项数据为0的数据
            List <Dict> dictListFind = dictService.findList (dict);

            // 将子项数据list 赋值给mvc model层返回给jsp页面
            model.addAttribute ("dictList", dictList);

            model.addAttribute ("dictListFind", dictListFind);

            // 将list赋值给CATEGORYSUBLIST放入缓存中
            session.setAttribute (DICTSUBLIST, dictList);
        } else {
            // 清空创建的子项
            session.setAttribute (DICTSUBLIST, new ArrayList <Dict> ());
        }

        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("dict", dict);

        // 返回页面地址
        return "modules/sys/dictListShowTwo";
    }


    @RequiresPermissions("database:message:edit")
    @ResponseBody
    @RequestMapping(value = "checkName")
    public String checkName(String itemCode, String oldItemValue, Dict dict) {


        try {
            if (itemCode != null && itemCode.toUpperCase ().equals (oldItemValue.toUpperCase ())) {
                // 返回true
                return "true";
                // 页面获取数据值与旧数据若不相同，查询结果为null，并且数据值不为null
            } else if (itemCode != null && dictService.getItemCode (itemCode) == null) {

                return "true";

            }
            // 数据值重名
            return "false";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }
        // 数据值未重名
        return "true";
    }

    /**
     * 保存信息
     *
     * @param dict
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(Dict dict, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (dict.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            Dict dictNew = get (dict.getId ().toString ());
            // 判断数据是否删除
            if (dictNew == null || BaseEntity.DEL_FLAG_DELETE.equals (dictNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (SystemMessageUtils.getMessageName ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
            // 排他处理
            if (dict.getVersion () == get (dict.getId ().toString ()).getVersion ()) {
                // 版本号加1
                dict.setVersion (dict.getVersion () + 1);
            } else {
                // 返回提示信息
                return renderString (response, AjaxDone.error (SystemMessageUtils.getMessageName ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
        } else {
            dict.setItemSort (0);

            // 新建版本号赋值1
            dict.setVersion (1L);
        }

        // 通过缓存将子项值赋给list
        List <Dict> list = (List <Dict>) session.getAttribute (DICTSUBLIST);

        // 将list赋给子项list
        dict.setDictList (list);

        // 若启用未选择赋值1
        if (dict.getEnableFlag () == null) {
            dict.setEnableFlag ("1");
        }
        // 保存基准数据及子项数据
        dictService.saveDict (dict);

        // 清空缓存,实例化
        session.setAttribute (DICTSUBLIST, new ArrayList <Dict> ());

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("dictSaveSuccess")));

    }

    /**
     * 删除信息
     *
     * @param dict
     * @param response
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "delete")
    public String delete(Dict dict, HttpServletResponse response) {

        try {

            // 执行逻辑删除方法
            dictService.deleteDict (dict);
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 提示错误信息
            return renderString (response, AjaxDone.error (SystemMessageUtils.getMessageName ("System_error_please_contact_your_administrator")));
        }

        // 提示删除成功信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("dict_delete_success")));
    }

    /**
     * 下载导入基础数据模板
     *
     * @param response
     * @return
     */
    @RequiresPermissions("database:message:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = getText ("dict_importTemplate");
            Dict dict = new Dict ();
            List <Dict> list = dictService.findAllListExport (dict);
            // dict_msg04 :基础数据
            new ExportExcel (getText ("dict_msg04"), Dict.class, 2).setDataList (list).write (response, fileName).dispose ();
            return null;
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }
        // 提示错误信息
        return renderString (response, AjaxDone.error (SystemMessageUtils.getMessageName ("System_error_please_contact_your_administrator")));

    }

    /**
     * 导入基础数据
     *
     * @param file
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    @ResponseBody
    public String importFile(MultipartFile file, HttpServletResponse response) throws InvalidFormatException, IOException, InstantiationException, IllegalAccessException {
        Integer successNum = 0;
        Integer failureNum = 0;
        StringBuilder failureMsg = new StringBuilder ();
        ImportExcel ei = new ImportExcel (file, 1, 0);
        List <Dict> list = ei.getDataList (Dict.class);

        // 判断数据值是否重复
        Set set = new HashSet (CollectionsUtils.extractToList (list, "itemValue"));
        if (list.size () != set.size ()) {
            failureMsg.append ("<br/>" + getText ("dict_msg02"));
            return renderString (response, AjaxDone.error (failureMsg.toString ()));
        }
        for (Dict dict : list) {
            try {
                if (StringUtils.isBlank (dict.getItemCode ())
                        || StringUtils.isBlank (dict.getItemValue ())
                        || StringUtils.isBlank (dict.getItemNameCn ())
                        || StringUtils.isBlank (dict.getItemNameEn ())
                        || StringUtils.isBlank (dict.getItemNameJp ())
                        || StringUtils.isBlank (dict.getItemSort ().toString ())) {
                    // dict_msg01 :必填项数据存在空值，请检查数据！
                    return renderString (response,
                            AjaxDone.error (getText ("dict_msg01")));
                }
            } catch (ConstraintViolationException ex) {
                // 记录日志
                logger.error (ex.getMessage (), ex);
                // dict_msg04 :基础数据 dict_msg05: 导入失败：
                failureMsg.append ("<br/>" + getText ("dict_msg04") + dict.getItemCode () + "-" + dict.getItemValue () + getText ("dict_msg05"));
                List <String> messageList = BeanValidators.extractPropertyAndMessageAsList (ex, ": ");
                for (String message : messageList) {
                    failureMsg.append (message + "; ");
                    failureNum++;
                }
            } catch (Exception ex) {
                // 记录日志
                logger.error (ex.getMessage (), ex);
                // dict_msg04: 基础数据 dict_msg05: 导入失败：
                failureMsg.append ("<br/>" + getText ("dict_msg04") + dict.getItemCode () + "-" + dict.getItemValue () + getText ("dict_msg05") + ex.getMessage ());
            }
        }
        if (failureNum > 0) {
            // dict_msg06:，失败 dict_msg07:条基础数据，导入信息如下：
            failureMsg.insert (0, getText ("dict_msg06") + failureNum + getText ("dict_msg07"));
            return renderString (response, AjaxDone.error (getText ("System_error_please_contact_your_administrator") + failureMsg.toString ()));
        } else {
            successNum = dictService.saveDictImport (list);
            // dict_msg08:已成功导入 dict_msg09:条基础数据"
            return renderString (response, AjaxDone.ok (getText ("dict_msg08") + successNum + getText ("dict_msg09")));
        }
    }


    /**
     * 删除信息
     *
     * @param dict
     * @param request
     * @param model
     * @param response
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "deleteALL")
    public String deleteALL(Dict dict, HttpServletResponse response) {

        try {

            // 执行逻辑删除方法
            dictService.deleteDictALL (dict);
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 提示错误信息
            return renderString (response, AjaxDone.error (getText ("System_error_please_contact_your_administrator")));
        }

        // 提示删除成功信息
        return renderString (response, AjaxDone.ok (getText ("dict_delete_success")));
    }


    /**
     * 进入编辑页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "formALL")
    public String formALL(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        // 执行查询方法查询子项数据为0的数据
        List <Dict> dictListFind = dictService.findList (dict);
        // 执行查询方法查询子项数据
        List <Dict> dictList = dictService.findListDict (dict);

        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dictListFind", dictListFind);
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute ("dictList", dictList);
        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("dict", dict);

        // 返回页面地址
        return "modules/sys/dictListShowTwo";
    }

    /**
     * 进入编辑页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "updateChild")
    public String updateChild(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        dictService.insertList (dict);

        // 返回页面地址
        return "modules/sys/dictEditTwo";
    }

    /**
     * 进入编辑页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "newSearch")
    public String newSearch(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        List <Dict> dictList = dictService.findListDict (dict);

        // 将查询结果赋值mvc model层返回jsp页面

        model.addAttribute ("dictList", dictList);

        // 返回页面地址
        return "modules/sys/dictListShowTwo";
    }

    /**
     * 进入编辑页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "formTwo")
    public String formTwo(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        // 新建判断 若不为null 编辑数据
        if (dict.getId () != null) {

            // 实力化子项实体类
            Dict dictSub = new Dict ();

            // 给子项实体类赋值（关联值——项目值）
            dictSub.setItemValue (dict.getItemValue ());

            // 执行查询方法查询子项数据
            List <Dict> dictList = dictService.findSubDict (dictSub);

            // 将子项数据list 赋值给mvc model层返回给jsp页面
            model.addAttribute ("dictList", dictList);

            // 将list赋值给CATEGORYSUBLIST放入缓存中
            session.setAttribute (DICTSUBLIST, dictList);
        } else {
            // 清空创建的子项
            session.setAttribute (DICTSUBLIST, new ArrayList <Dict> ());
        }

        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("dict", dict);

        // 返回页面地址
        return "modules/sys/dictEditTwo";
    }

    /**
     * 进入编辑页面
     *
     * @param dict
     * @param model
     * @return
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "formThree")
    public String formThree(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {


        model.addAttribute ("dict", dict);
        // 返回页面地址
        return "modules/sys/dictEditTwo";
    }


    /**
     * 保存信息
     *
     * @param dict
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "saveALL")
    @ResponseBody
    public String saveALL(Dict dict, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (dict.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            Dict dictNew = get (dict.getId ().toString ());
            // 判断数据是否删除
            if (dictNew == null || BaseEntity.DEL_FLAG_DELETE.equals (dictNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }

            // 排他处理
            if (dict.getVersion () == get (dict.getId ().toString ()).getVersion ()) {

                // 版本号加1
                dict.setVersion (dict.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
        } else {

            // 新建版本号赋值1
            dict.setVersion (1L);
        }

        // 通过缓存将子项值赋给list
        List <Dict> list = (List <Dict>) session.getAttribute (DICTSUBLIST);

        // 将list赋给子项list
        dict.setDictList (list);

        // 若启用未选择赋值1
        if (dict.getEnableFlag () == null) {
            dict.setEnableFlag ("1");
        }
        // 保存基准数据及子项数据
        dictService.saveDictALL (dict);

        // 清空缓存,实例化
        session.setAttribute (DICTSUBLIST, new ArrayList <Dict> ());

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("dictSaveSuccess")));

    }

    /**
     * @param @param  category
     * @param @param  redirectAttributes
     * @param @param  model
     * @param @return
     * @return String
     * @throws
     * @Title: formSub
     * @Description: 新建子项
     */
    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "formSub")
    public String formSub(Dict dict, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        int delIndex = dict.getDelIndex ();
        if (delIndex != -1) {
            // 获取当前创建的子项
            List <Dict> listSubItems = (List <Dict>) session.getAttribute (DICTSUBLIST);
            dict = listSubItems.get (delIndex);
            dict.setDelIndex (delIndex);
        }

        // 新建子项 将Category实体类赋给mvc model层 返回jsp页面
        model.addAttribute ("dict", dict);

        // 返回页面地址
        return "modules/sys/dictEditTwo";
    }

    /**
     * @param @param  category
     * @param @param  model
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: deleteSub
     * @Description: 删除缓存子项数据
     */

    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "deleteSub")
    public String deleteSub(Dict dict, Model model, HttpSession session) {
        try {

            // 通过缓存获取子项数据
            List <Dict> dictList = (List <Dict>) session.getAttribute (DICTSUBLIST);

            // 删除子项
            dictList.remove (dict.getDelIndex ());

            // 在session里重新存入子项
            session.setAttribute (DICTSUBLIST, dictList);

            // 将list赋值给mvc model层返回jsp 页面
            model.addAttribute ("dictList", dictList);

            // 返回地址
            return "modules/sys/dictListShowTwo";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 返回地址
            return "modules/sys/dictListShowTwo";
        }

    }

    /**
     * @param @param  category
     * @param @param  request
     * @param @param  model
     * @param @param  response
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: saveSub
     * @Description: 保存子项数据赋值给缓存list
     */

    @RequiresPermissions("database:message:edit")
    @RequestMapping(value = "saveSub")
    @ResponseBody
    public String saveSub(Dict dict, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) {
        try {

            // 通过缓存获取list数据
            List <Dict> dictList = (List <Dict>) session.getAttribute (DICTSUBLIST);

            // 将新的实体类添加到list中
            int delIndex = dict.getDelIndex ();

            if (delIndex == -1) {
                dictList.add (dict);
            } else {
                dictList.remove (delIndex);
                dictList.add (delIndex, dict);
            }

            // 将list赋值给缓存session
            session.setAttribute (DICTSUBLIST, dictList);

            // 返回true
            return "true";

        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 抛异常返回false
            return "false";
        }

    }

    /**
     * @param @param  category
     * @param @param  model
     * @param @param  session
     * @param @return
     * @return String
     * @throws
     * @Title: searchSubList
     * @Description: 根据父项value, 查找相关子项
     */

    @RequiresPermissions("database:message:view")
    @RequestMapping(value = "searchSubList")
    public String searchSubList(Dict dict, Model model, HttpSession session) {
        try {

            // 通过缓存赋值给子项list
            List <Dict> dictList = (List <Dict>) session.getAttribute (DICTSUBLIST);

            // 将list赋值给 mvc model层返回jsp页面
            model.addAttribute ("dictList", dictList);

            // 返回地址
            return "modules/sys/dictListShowTwo";
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
            // 发生异常 不返回
            return null;
        }
    }
}
